package com.liting.uitest.service.impl;

import com.alibaba.fastjson2.JSON;
import com.liting.uitest.entity.FileInfo;
import com.liting.uitest.entity.FileTestResult;
import com.liting.uitest.model.ImageInfo;
import com.liting.uitest.service.FileInfoService;
import com.liting.uitest.service.FileTestService;
import lombok.Synchronized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ImageCacheService {
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private FileTestService testService;

    private static Map<Long, ImageInfo> imageInfoMap = new HashMap<>();

    private static Map<Long, Map<String, Object>> imageTestMap = new HashMap<>();

    @Synchronized
    public void addImageTestResult(Long fileId, String testMethod, Object testResult) {
        Map<String, Object> testResultMap = getImageTestMap(fileId);

        testResultMap.put(testMethod, testResult);


        FileTestResult fileTest = new FileTestResult();
        fileTest.setFileId(fileId);
        fileTest.setTestResult(JSON.toJSONString(testResultMap));
        fileTest.setTestTime(new Date());

        testService.saveOrUpdate(fileTest);

        imageTestMap.put(fileId, testResultMap);
    }

    public Map<String, Object> getImageTestMap(Long fileId) {
        Map<String, Object> testResultMap = imageTestMap.get(fileId);
        if (testResultMap == null) {
            FileTestResult testResult = testService.getById(fileId);
            if (testResult == null) {
                testResultMap = new HashMap<>();
            } else {
                testResultMap = JSON.parseObject(testResult.getTestResult());
            }
        }

        imageTestMap.put(fileId, testResultMap);

        return testResultMap;
    }

    public void addImage(FileInfo fileInfo) {
        ImageInfo imageInfo = new ImageInfo(fileInfo);
        imageInfoMap.put(fileInfo.getId(), imageInfo);
    }

    public ImageInfo getImage(Long fileId) {
        ImageInfo imageInfo = imageInfoMap.get(fileId);
        if (imageInfo == null) {
            FileInfo fileInfo = fileInfoService.getFile(fileId);
            if (fileInfo != null) {
                imageInfo = new ImageInfo(fileInfo);
                imageInfoMap.put(fileInfo.getId(), imageInfo);
            } else {
                return null;
            }
        }
        return imageInfo;
    }

    @Scheduled(cron = "0 0 */1 * * ?")
    public void clear() {
        imageInfoMap.clear();
        imageTestMap.clear();
    }

}
